package com.example.client.handler;

import com.example.client.GomokuGameClient;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class SigninHandler1 implements Runnable {
    private final String username;
    private final String password;
    private boolean success = false;

    public SigninHandler1(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public void run() {
        HttpURLConnection conn = null;
        try {
            // 建立 HTTP 连接，根据你的服务器IP修改
            URL url = new URL("http://192.168.1.31:8080/signin");
            conn = (HttpURLConnection) url.openConnection();

            // 配置表单格式请求
            conn.setRequestMethod("POST");  //设置为POST请求
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //使用表单格式提交数据
            conn.setRequestProperty("Accept", "*/*");
            conn.setDoOutput(true); //允许输入数据

            // 构建表单参数
            String params = "username=" + URLEncoder.encode(username, "UTF-8") +
                    "&password=" + URLEncoder.encode(password, "UTF-8");

            // 向服务器发送访问数据
            try (OutputStream os = conn.getOutputStream()) {
                os.write(params.getBytes(StandardCharsets.UTF_8));
            }

            // 处理服务器反馈
            int status = conn.getResponseCode();
            if (status == 200) {
                try (InputStream is = conn.getInputStream()) {
                    String response = new String(is.readAllBytes(), StandardCharsets.UTF_8);
                    System.out.println(response);

                    if (response.contains("成功")) {  //200时读取响应内容，如果包含"成功"则启动游戏
                        try {
                            new GomokuGameClient();
                        } catch (Exception e) {     //非200时读取错误信息并抛出异常
                            throw new RuntimeException(e);
                        }
                    }
                }
            } else {
                try (InputStream es = conn.getErrorStream()) {
                    String error = es == null ? "" : new String(es.readAllBytes(), StandardCharsets.UTF_8);
                    throw new IOException("HTTP " + status + ": " + error);
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (conn != null) {     //资源清理
                conn.disconnect();
            }
        }
    }
}